import { computed, ref, shallowRef, watch, watchEffect } from 'vue'
import { defineStore } from 'pinia'
import breakpoints, { updateHtmlFontSize } from '@/breakpoints'

export type Tag = {
  name: string
  path: string
  meta: {
    title?: string
  }
}

export const useTagStore = defineStore('tag', () => {
  const aliveTabKey = computed(() => {
    return tags.value
      .map((tag) => tagsNameForComponentName.value[tag.name])
      .filter(Boolean) as string[]
  })
  const tags = ref<Tag[]>([])
  const tagsNameForComponentName = ref<Record<string, string>>({})
  const setTagTitle = (path: string, title: string) => {
    const tag = tags.value.find((tag) => tag.path === path)
    if (!tag) return
    tag.meta.title = title
  }

  const closeTag = shallowRef<any>(() => {})
  const closeTagByName = shallowRef<any>(() => {})

  return {
    tags,
    aliveTabKey,
    setTagTitle,
    tagsNameForComponentName,
    closeTag,
    closeTagByName,
    clear: () => {
      tags.value = []
      tagsNameForComponentName.value = {}
    }
  }
})

export const useLayoutStore = defineStore('layout', () => {
  // sidebar
  const type = import.meta.env.VITE_TYPE
  const sidebarCollapsed = ref(false)
  const sidebarCollapsedWidth = ref(45)
  const sidebarWidth = ref(210)
  const sidebarNowWidth = computed(() =>
    sidebarCollapsed.value ? sidebarCollapsedWidth.value : sidebarWidth.value
  )
  // points control sidebar collapse
  const greaterLaptop = breakpoints.greater('l')
  watchEffect(() => {
    if (type != 'pad') sidebarCollapsed.value = !greaterLaptop.value
  })

  const current = breakpoints.current()
  watch(current, () => updateHtmlFontSize(), { immediate: true })

  // header
  const tagsHeight = ref(34)
  const headerHeight = ref(52)
  const headerMarginBottom = ref(9)

  return {
    sidebarCollapsed,
    sidebarCollapsedWidth,
    sidebarWidth,
    sidebarNowWidth,
    tagsHeight,
    headerHeight,
    headerMarginBottom
  }
})
